package com.example.testluckyroulette

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.*
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import com.example.testluckyroulette.bean.LuckyPersonBean

/**
 * Create Time:2020/9/14
 * Author: Lindanrong
 * Description:一个完整的轮盘
 */
class LuckyRouletteView : View {
    var mContext: Context

    var isPend = false//判断如果所有的item的bitmap是否加载完成
    var mSum = 0 //传入的item的总数
    var mPreStartIndex = 0 //已经准备好的bitmap

    private var mRepeatCount = 6 //转几圈
    private var mStartAngle = 0f //存储圆盘开始的位置
    private var mItemAngle = 0f//每个item的角度

    var mWith = 0 //控件的宽度
    var mHeight = 0 //控件的高度

    var mRadio: Int = 0 //圆盘的半径
    var mBackRoundRect: RectF = RectF()//圆盘的矩形
    var mBackRoundPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) //背景圆盘

    var mTextX = 0f //字体的位置
    var mTextY = 0f //字体的位置
    var mTextSize = 0f //字体大小
    var mTextColor =  Color.BLACK
    var mTextPaint = Paint(Paint.ANTI_ALIAS_FLAG) //转盘文字画笔

    //头像的圆的矩阵
    private val mDrawableRect = RectF()

    //头像的背景圆的矩阵
    private val mBorderRect = RectF()

    //头像的画笔笔头
    private var mBitmapShader: BitmapShader? = null

    //头像的矩阵
    private val mShaderMatrix = Matrix()

    //头像的画笔
    private val mBitmapPaint = Paint(Paint.ANTI_ALIAS_FLAG)

    //头像背景圆的画笔
    private val mBorderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    var mAvatarRadio: Int = 0 //头像的半径
    //头像背景的圈
    private var mBorderColor: Int = Color.BLACK
    private var mBorderWidth: Int = 0

    lateinit var mLuckyPerson: LuckyPersonBean
    private var objectAnimator: ObjectAnimator? = null


    private lateinit var mLuckyPersonBeanList: MutableList<LuckyPersonBean>
    var mHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            isPend = true
            invalidate()
            startAnimal()
        }
    }


    constructor(context: Context) : this(context, null)

    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)

    constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attributeSet,
        defStyleAttr
    ) {
        mContext = context
        var ta =  context.obtainStyledAttributes(attributeSet!!,R.styleable.LuckyRouletteView)
        mBorderColor =  ta.getColor(R.styleable.LuckyRouletteView_avatar_background,Color.BLACK)
        mTextColor =  ta.getColor(R.styleable.LuckyRouletteView_name_color,Color.BLACK)
        mTextSize = ta.getDimension(R.styleable.LuckyRouletteView_name_size,20f)
        mBorderWidth = ta.getDimension(R.styleable.LuckyRouletteView_avatar_border_size,0f).toInt()
        ta.recycle()
        init()
    }


    /**
     * 初始化主要初始化一些画笔什么的
     */
    private fun init() {
        mTextPaint.color = mTextColor
        mTextPaint.strokeWidth = 3f
        mTextPaint.textAlign = Paint.Align.CENTER
        mTextPaint.textSize = mTextSize
    }

    /**
     * 加载数据进来
     */
    fun setData(
        luckyPersonBeanList: MutableList<LuckyPersonBean>,
        id:Int) {
        mLuckyPersonBeanList = luckyPersonBeanList
        mSum = luckyPersonBeanList.size
        mItemAngle = 360f / mSum   //计算每个item的角度
        for (i in 0 until mSum) {
            luckyPersonBeanList[i].mCenterAngle =
                mStartAngle + mItemAngle * i + mItemAngle / 2 //计算出每个item的中心angle
            var a = luckyPersonBeanList[i].avatar
            luckyPersonBeanList[i].setAvatar(
                mContext, a, R.mipmap.default_avatar
            ) {
                mPreStartIndex++
                if (mPreStartIndex == mSum) {
                    mHandler.sendEmptyMessage(0)
                }
            }
            if(luckyPersonBeanList[i].id == id){
                mLuckyPerson = luckyPersonBeanList[i]
            }
        }

    }

    /**
     * 清楚上次滚动带来的数据叠加
     */
    fun clear(){
         isPend = false//判断如果所有的item的bitmap是否加载完成
         mSum = 0 //传入的item的总数
         mPreStartIndex = 0 //已经准备好的bitmap
        mStartAngle = 0f //存储圆盘开始的位置
        mItemAngle = 0f//每个item的角度
    }


    /**
     * 计算字体存在的位置
     */
    private fun calculateTextLocal() {
        //名字的矩阵位置距离圆心4/10的地方  用于不画弧度的
        mTextX = mRadio.toFloat()
        mTextY = mRadio * 6 / 10f   //6/10是屏幕距离文字的地方
    }

    /**
     * 计算一下头像所在的位置
     */
    private fun calculateAvatarRetF() {
        //设置背景 + 头像的位置
        mBorderRect.set(
            mRadio - mAvatarRadio.toFloat(),
            mRadio.toFloat()/3 - mAvatarRadio,
            mRadio + mAvatarRadio.toFloat(),
            mRadio.toFloat()/3 + mAvatarRadio
        )
        mDrawableRect.set(
            mRadio - mAvatarRadio.toFloat(),
            mRadio.toFloat()/3 - mAvatarRadio,
            mRadio + mAvatarRadio.toFloat(),
            mRadio.toFloat()/3 + mAvatarRadio
        )
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mWith = MeasureSpec.getSize(widthMeasureSpec)
        mHeight = MeasureSpec.getSize(heightMeasureSpec)
        //设置半径
        mRadio = mWith.coerceAtMost(mHeight) / 2  //求出两个值哪个比较小
        //确定一下圆心的坐标
        mBackRoundRect.run {
            top = 0f
            left = 0f
            right = mRadio * 2f
            bottom = mRadio * 2f
        }
        mAvatarRadio = mRadio/6
        //计算一下字体的位置
        calculateTextLocal()
        //计算头像所在的位置
        calculateAvatarRetF()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if(!isPend) return
        // 先旋转 后作画图 （作画后再旋转就没用了）
        canvas.rotate(-90f, mRadio.toFloat(), mRadio.toFloat())
        //画各个item的扇形
        //画名字
        //画头像
        for (index in 0 until mSum) {
            drawCircular(canvas, index)
            drawName(canvas,index)
            drawCircleAvatar(canvas, index)
        }
    }


    /**
     * 画扇形
     */
    private fun drawCircular(canvas: Canvas, index: Int) {
        //设置画笔颜色
        mBackRoundPaint.color = mContext.resources.getColor(mLuckyPersonBeanList[index].color)
        canvas.drawArc(
            mBackRoundRect,
            mStartAngle + mItemAngle * index,
            mItemAngle,
            true,
            mBackRoundPaint
        )
    }

    /**
     * 画名字
     */
    fun drawName(canvas: Canvas,index: Int) {
        canvas.save() //save()跟restore()要成对存在 -- 表示在save到restore中的旋转放大缩小等 只对这两方法间的绘画起作用
        canvas.rotate(90f, mRadio.toFloat(), mRadio.toFloat()) //将原来的画布-90旋转回来90回来
        canvas.rotate(
            mLuckyPersonBeanList[index].mCenterAngle,
            mRadio.toFloat(),
            mRadio.toFloat()
        )// 再进行item中心角度的旋转，并画头像
        canvas.drawText(mLuckyPersonBeanList[index].name, mTextX, mTextY, mTextPaint)
        canvas.restore()
    }

    /**
     * 画头像
     */
    private fun drawCircleAvatar(canvas: Canvas, i: Int) {
        mBitmapShader = BitmapShader(
            mLuckyPersonBeanList[i].avatarBitmap,
            Shader.TileMode.CLAMP,
            Shader.TileMode.CLAMP
        )
        mBitmapPaint.apply {
            isAntiAlias = true
            shader = mBitmapShader
        }
        mBorderPaint.apply {
            style = Paint.Style.FILL
            isAntiAlias = true
            color = mBorderColor
        }
        updateShaderMatrix(mLuckyPersonBeanList[i].avatarBitmap)//对图片进行缩小跟移动中心点
        canvas.save() //save()跟restore()要成对存在 -- 表示在save到restore中的旋转放大缩小等 只对这两方法间的绘画起作用
        canvas.rotate(90f, mRadio.toFloat(), mRadio.toFloat()) //将原来的画布-90旋转回来90回来
        canvas.rotate(
            mLuckyPersonBeanList[i].mCenterAngle,
            mRadio.toFloat(),
            mRadio.toFloat()
        )// 再进行item中心角度的旋转，并画头像
        canvas.drawCircle(
            mDrawableRect.centerX(),
            mDrawableRect.centerY(),
            mAvatarRadio.toFloat() + mBorderWidth,
            mBorderPaint
        )
        canvas.drawCircle(
            mDrawableRect.centerX(),
            mDrawableRect.centerY(),
            mAvatarRadio.toFloat(),
            mBitmapPaint
        )
        canvas.restore()
    }

    /**
     * 对图片进行缩小跟移动中心点
     */
    private fun updateShaderMatrix(oldbitmap: Bitmap) {
        mShaderMatrix.set(null)
        val scale = mDrawableRect.width() / oldbitmap.width.toFloat()
        var dx = (mDrawableRect.width() - oldbitmap.width * scale) * 0.5f
        var dy = (mDrawableRect.height() - oldbitmap.height * scale) * 0.5f
        mShaderMatrix.setScale(scale, scale)
        mShaderMatrix.postTranslate(
            (dx + 0.5f).toInt() +
                    /**起始位置也要加上**/
                    mDrawableRect.left,
            (dy + 0.5f).toInt() +
                    /**起始位置也要加上**/
                    mDrawableRect.top
        )
        mBitmapShader!!.setLocalMatrix(mShaderMatrix)
    }

    /**
     * 开始动画
     */
    fun startAnimal() {
        objectAnimator?.cancel()
        objectAnimator = ObjectAnimator.ofFloat(
            this,
            "rotation",
            mStartAngle,
            mStartAngle + mRepeatCount * 360 + (360 - mLuckyPerson.mCenterAngle.toInt())
        ).apply {
            interpolator = AccelerateDecelerateInterpolator()
            duration = 5000
            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator) {
                    super.onAnimationEnd(animation)
                    Log.d(
                        Companion.TAG,
                        "onAnimationEnd: ${mLuckyPerson.mCenterAngle}+${mLuckyPerson.name}"
                    )
                }
            })
            start()
        }
    }

    companion object {
        private const val TAG = "LuckyRouletteView"
    }
}